package com.zf.zffencheng.conf;

import com.zf.zffencheng.interceptor.SapiInterceptor;
import com.zf.zffencheng.interceptor.TenantInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * ClassName: WebConfig <br/>
 * Description:  <br/>
 * date: 2021/5/7 10:05<br/>
 *
 * @author william <br/>
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private SapiInterceptor sapiInterceptor;
    @Autowired
    private TenantInterceptor tenantInterceptor;
    /**
     *  跨域
     * @return CorsConfiguration
     */
    private CorsConfiguration corsConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.setMaxAge(3600L);
        return corsConfiguration;
    }
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfig());
        return new CorsFilter(source);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        String[] ignore = {"/swagger-ui.html", "/webjars/**", "/sapi/sms/**"};
        registry.addInterceptor(sapiInterceptor).addPathPatterns("/sapi/**").excludePathPatterns(ignore).order(1);
        registry.addInterceptor(tenantInterceptor).addPathPatterns("/sapi/tenant/**").excludePathPatterns(ignore).order(2);
    }


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/");
        // 解决 SWAGGER 404报错
        registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}
